package com.example.myapplication

import android.Manifest
import android.annotation.SuppressLint
import android.app.ProgressDialog
import android.content.DialogInterface
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.FileIOUtils
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.ImageUtils
import com.blankj.utilcode.util.PathUtils
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.PermissionUtils.SimpleCallback
import com.blankj.utilcode.util.ResourceUtils
import com.example.myapplication.util.BitmapUtils
import com.example.myapplication.util.ImageUtil
import com.google.gson.Gson
import com.wakeup.sdk.ble.WeikeBleMgr
import com.wakeup.sdk.ble.ext.BaseCallback
import com.wakeup.sdk.ble.ext.CustomDialBean
import com.wakeup.sdk.ble.ext.EventType
import com.wakeup.sdk.ble.ext.OnEventListener
import com.wakeup.sdk.ble.ext.connect.DeviceState
import com.wakeup.sdk.ble.ext.other.DialStyle
import com.wakeup.sdk.ble.ext.settings.DeviceSettingsMgr
import com.wakeup.sdk.ble.ext.settings.model.ContactSettings
import com.wakeup.sdk.ble.ext.settings.model.DeviceUserModel
import com.wakeup.sdk.ble.ext.weather.WeatherAllInfo
import com.wakeup.sdk.ble.utils.BleUtil
import com.wakeup.sdk.ble.utils.DeviceInfoDao
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

/**
 * @Author:  zgh
 * @CreateDate:  2023/10/9 15:52
 * @Description: 连接成功后的功能界面
 */
class DeviceActivity : AppCompatActivity() {

    lateinit var contentTv: TextView
    private val TAG: String = DeviceActivity::class.java.name
    private val deviceUserModel = DeviceUserModel(0, 18, 170, 60f, 70, 10000, 0, 0, 0)

    private val mProgressDialog by lazy { ProgressDialog(this) }

    private val callback = object : OnEventListener {
        override fun onEvent(type: EventType, code: Int, data: Any?) {
            Log.i(TAG, "type = $type ; code = $code ; data = $data")
            when (type) {
                EventType.TYPE_DEVICE_STATE -> {
                    if (code == DeviceState.STATE_CONNECT_FAIL || code == DeviceState.STATE_NO_CONNECTION) {
                        finish()
                    }
                }

                EventType.TYPE_SYNC_DATA -> {
                    val content = contentTv.text.toString()
                    data?.let {
                        contentTv.text = if (content.length > 1000) {
                            it.toString()
                        } else {
                            content.plus("\n$it")
                        }
                    }
                }

                EventType.TYPE_REQUEST_AVATAR -> {
                    data?.let {
                        WeikeBleMgr.setUserAvatarNickName(this@DeviceActivity,
                            WeikeBleMgr.getLastMac(),
                            it as Int,
                            BitmapFactory.decodeResource(
                                this@DeviceActivity.resources,
                                R.mipmap.image_default_avatar
                            ),
                            "我abc123",
                            object : BaseCallback<Int>() {
                                override fun callback(code: Int, t: Int) {
                                    Log.d(TAG, "send avatar code = $code ; status = $t")
                                }
                            })
                    }
                }

                EventType.TYPE_REQUEST_DATA -> {
                    when (code) {
                        // 血糖
                        0 -> WeikeBleMgr.sendBloodSugar(arrayListOf(4.5f, 5.5f, 3.4f))
                        // 呼吸频率
                        1 -> WeikeBleMgr.sendBreathe(deviceUserModel, arrayListOf(80, 90, 70))
                        // 体重
                        2 -> WeikeBleMgr.sendWeight(arrayListOf(60.66f, 70.0f, 80.0f))
                        // bmi
                        3 -> WeikeBleMgr.sendBmi(deviceUserModel, arrayListOf(60.0f, 70.0f, 80.0f))
                        else -> {}
                    }
                }

                EventType.TYPE_AVAILABLE_MEMORY -> {
                    // code 0表盘市场 1应用市场 2本地音乐
                    val typeDesc = when (code) {
                        0 -> "表盘市场"
                        1 -> "应用市场"
                        2 -> "本地音乐"
                        else -> ""
                    }
                    Toast.makeText(
                        this@DeviceActivity,
                        "${typeDesc}剩余${data}kb空间",
                        Toast.LENGTH_SHORT
                    ).show()
                }

                EventType.TYPE_APP_PACKAGE_NAME -> {
                    Log.i(TAG, "设备已安装的应用信息 = $data")
                }

                EventType.TYPE_DEVICE_TAKE -> {
                    Log.i(TAG, "设备发起拍照")
                    Toast.makeText(this@DeviceActivity, "设备发起拍照", Toast.LENGTH_SHORT)
                        .show()
                }
                EventType.TYPE_RECEIVE_FILE -> {
                    if(code == 1) {
                        val progress = data as Long
                        Log.i(TAG, "receive progress: $progress")
                        return
                    }
                    if (code == -1){
                        Log.i(TAG, "传输异常中断")
                        return
                    }
                    if (code == -2){
                        Log.i(TAG, "传输取消")
                        return
                    }
                    if (code == 2) {
                        val path = data as String
                        Log.i(TAG, "传输完成保存数据 path: $path")
                    }
                }
                EventType.TYPE_DEVICE_FIND -> {
                    Log.i(TAG, "查找手机 code: $code")
                }
                else -> {}
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_device)
        // 连接状态
        WeikeBleMgr.registerListener(callback, EventType.TYPE_DEVICE_STATE)
        // 同步数据
        WeikeBleMgr.registerListener(callback, EventType.TYPE_SYNC_DATA)
        // 发送数据回调
        WeikeBleMgr.registerListener(callback, EventType.TYPE_DEVICE_WRITE)
        // 同步数据结束
        WeikeBleMgr.registerListener(callback, EventType.TYPE_SYNC_OVER)
        // 摇摇拍照
        WeikeBleMgr.registerListener(callback, EventType.TYPE_DEVICE_TAKE)
        // 设备电量
        WeikeBleMgr.registerListener(callback, EventType.TYPE_DEVICE_BATTERY)
        // 查找手机
        WeikeBleMgr.registerListener(callback, EventType.TYPE_DEVICE_FIND)
        // 设备请求用户头像
        WeikeBleMgr.registerListener(callback, EventType.TYPE_REQUEST_AVATAR)
        // 设备请求同步数据
        WeikeBleMgr.registerListener(callback, EventType.TYPE_REQUEST_DATA)
        // 设备返回可用存储空间
        WeikeBleMgr.registerListener(callback, EventType.TYPE_AVAILABLE_MEMORY)
        // 设备返回已安装应用信息
        WeikeBleMgr.registerListener(callback, EventType.TYPE_APP_PACKAGE_NAME)
        // 设备发起拍照
        WeikeBleMgr.registerListener(callback, EventType.TYPE_DEVICE_TAKE)
        // 文件传输接收
        WeikeBleMgr.registerListener(callback, EventType.TYPE_RECEIVE_FILE)
        //  添加自定义协议解析
        WeikeBleMgr.addBleAnalyzer(CustomAnalyzer())
        WeikeBleMgr.sendSettingsCRC(1, 0, 999)
        WeikeBleMgr.sendSettingsCRC(0, 0, 998)
        val connectDevice = WeikeBleMgr.getConnectDevice()
        if (connectDevice != null) {
            findViewById<TextView>(R.id.deviceStateTv).text =
                "name: ${connectDevice.bleName} \nmac: ${(connectDevice.mac)}"
        }
        contentTv = findViewById(R.id.contentTv)
        contentTv.movementMethod = ScrollingMovementMethod.getInstance()

        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
        mProgressDialog.setCancelable(false)

        // 同步数据
        findViewById<View>(R.id.sync).setOnClickListener { WeikeBleMgr.syncData() }
        // 久坐提醒
        findViewById<View>(R.id.sedentaryRemind).setOnClickListener {
            val settings = DeviceSettingsMgr.getSetting(WeikeBleMgr.getLastMac())
            settings.sedentaryRemind.apply {
                // 默认为关  开始时间为9点  结束时间为22点  提醒间隔为45
                switch = true
                startTime = 9 * 60
                endTime = 22 * 60
                intervalTime = 45
            }
            DeviceSettingsMgr.saveSetting(settings)
            WeikeBleMgr.setSedentaryRemind(settings.sedentaryRemind)
            WeikeBleMgr.setAllReminderSwitch(settings.getSwitch1(), settings.getSwitch2())
        }
        // 喝水提醒
        findViewById<View>(R.id.waterRemind).setOnClickListener {
            val settings = DeviceSettingsMgr.getSetting(WeikeBleMgr.getLastMac())
            settings.waterRemind.apply {
                // 默认为关  开始时间为9点  结束时间为22点  提醒间隔为45
                switch = true
                startTime = 9 * 60
                endTime = 22 * 60
                intervalTime = 45
            }
            DeviceSettingsMgr.saveSetting(settings)
            WeikeBleMgr.setWaterRemind(settings.waterRemind)
            WeikeBleMgr.setAllReminderSwitch(settings.getSwitch1(), settings.getSwitch2())
        }
        // 心率提醒
        findViewById<View>(R.id.heartRemind).setOnClickListener {
            WeikeBleMgr.setHeartRemind(
                DeviceSettingsMgr.getSetting(WeikeBleMgr.getLastMac()).heartRemind.apply {
                    // 默认为关 警戒值为100
                    switch = false
                    count = 100
                }
            )
        }
        // 远眺提醒
        findViewById<View>(R.id.overlookRemind).setOnClickListener {
            WeikeBleMgr.setOverlookRemind(
                DeviceSettingsMgr.getSetting(WeikeBleMgr.getLastMac()).overlookRemind.apply {
                    switch = false // 默认关
                    // 提醒间隔为45
                    intervalTime = 45
                }
            )
        }
        // 运动提醒
        findViewById<View>(R.id.sportRemind).setOnClickListener {
            WeikeBleMgr.setSportRemind(
                DeviceSettingsMgr.getSetting(WeikeBleMgr.getLastMac()).sportRemind.apply {
                    // 默认为关 提醒时间为点
                    switch = false
                    remindTime = 8 * 60
                    repeatDay = 0x01 shl 7
                }
            )
        }
        // 吃药提醒
        findViewById<View>(R.id.medicineRemind).setOnClickListener {
            WeikeBleMgr.setMedicineRemind(
                DeviceSettingsMgr.getSetting(WeikeBleMgr.getLastMac()).medicineRemind.apply {
                    // 默认为关 提醒时间为点
                    switch = false
                    remindTime = 8 * 60
                    repeatDay = 0x01 shl 7
                }
            )
        }
        // 看书提醒
        findViewById<View>(R.id.bookRemind).setOnClickListener {
            WeikeBleMgr.setBookRemind(
                DeviceSettingsMgr.getSetting(WeikeBleMgr.getLastMac()).bookRemind.apply {
                    // 默认为关 提醒时间为点
                    switch = false
                    remindTime = 8 * 60
                    repeatDay = 0x01 shl 7
                }
            )
        }
        // 抬手亮屏开关
        findViewById<View>(R.id.lightScreen).setOnClickListener { WeikeBleMgr.setLightScreen(true) }
        // 查找设备
        findViewById<View>(R.id.findDevice).setOnClickListener { WeikeBleMgr.findBand() }
        // 12小时制开关
        findViewById<View>(R.id.hourSwitch).setOnClickListener { WeikeBleMgr.set12HourSwitch(true) }
        // 健康提醒开关
        findViewById<View>(R.id.reminderSwitch).setOnClickListener {
            val settings = DeviceSettingsMgr.getSetting(WeikeBleMgr.getLastMac())
            WeikeBleMgr.setAllReminderSwitch(settings.getSwitch1(), settings.getSwitch2())
        }
        // 勿扰设置
        findViewById<View>(R.id.noDisturbSetting).setOnClickListener {
            WeikeBleMgr.setNoDisturbModel(
                DeviceSettingsMgr.getSetting(WeikeBleMgr.getLastMac()).noDisturbSettings.apply {
                    switch = 0 // 默认关
                    startTime = 8 * 60
                    endTime = 22 * 60
                }
            )
        }
        // 勿扰开关
        findViewById<View>(R.id.noDisturbSwitch).setOnClickListener {
            WeikeBleMgr.setNoDisturbSwitch(
                DeviceSettingsMgr.getSetting(WeikeBleMgr.getLastMac()).noDisturbSettings.apply {
                    switch = 0 // 默认关
                }
            )
        }
        // 心率预警设置
        findViewById<View>(R.id.heartWarnSetting).setOnClickListener {
            WeikeBleMgr.setHeartSettings(
                DeviceSettingsMgr.getSetting(WeikeBleMgr.getLastMac()).heartSettings.apply {
                    // 有氧
                    aerobicHeartSwitch = true
                    aerobicMax = 150
                    // 静息心率
                    staticHeartSwitch = false
                    staticHeartMax = 150
                    staticHeartMin = 40
                    // 睡眠心率
                    sleepHeartSwitch = false
                    sleepHeartMax = 150
                    sleepHeartMin = 40
                }
            )
        }
        // 运动设置
        findViewById<View>(R.id.sportSetting).setOnClickListener {
            WeikeBleMgr.setSportSettings(
                DeviceSettingsMgr.getSetting(WeikeBleMgr.getLastMac()).sportSettings.apply {
                    // 自动暂停
                    autoPauseSwitch = true
                    // 开始提醒
                    startRemindSwitch = true
                    // 结束提醒
                    endRemindSwitch = true
                    // 按下暂停
                    keyPauseSwitch = false
                }
            )
        }
        // 睡眠设置开关
        findViewById<View>(R.id.sleepSwitch).setOnClickListener {
            WeikeBleMgr.setSleepSettingsSwitch(
                DeviceSettingsMgr.getSetting(WeikeBleMgr.getLastMac()).sleepSettings.apply {
                    //  自动开关
                    autoSwitch = false
                    //  显示时间
                    showTimeSwitch = false
                    // 睡眠跟踪
                    trackingSwitch = false
                    // 充电提醒开关
                    chargeRemindSwitch = false
                }
            )
        }
        // 睡眠设置范围
        findViewById<View>(R.id.sleepRange).setOnClickListener {
            WeikeBleMgr.setSleepSettingsRange(
                DeviceSettingsMgr.getSetting(WeikeBleMgr.getLastMac()).sleepSettings.apply {
                    // 时间范围
                    startTime = 22 * 60
                    endTime = 8 * 60
                }
            )
        }
        // 语言设置
        findViewById<View>(R.id.language).setOnClickListener {
            // 0: 简体中文  1：英语  2：意大利语  3：西班牙语  4：葡萄牙语  5：俄语  6：日语  7：繁体中文  8：德语  9：韩语
            // 10：泰语  11：阿拉伯语  12：土耳其语  13：法语  14：波兰语  15：印尼语  16：马来语  17：波斯语  18：希腊语  19：希伯来语
            // 20：捷克语  21：拉丁语  22：罗马尼亚语  23：荷兰语  24：越南语  25：丹麦语  26：瑞典语  27：挪威语  28：芬兰语  29：乌克兰语
            WeikeBleMgr.setLanguage(0)
        }
        // 消息通知设置开关
        findViewById<View>(R.id.notifySwitch).setOnClickListener {
            WeikeBleMgr.setNotifySwitch(
                DeviceSettingsMgr.getSetting(WeikeBleMgr.getLastMac()).notifySettings.apply {
                    //红点提示
                    redPointSwitch = false
                    //通知提示
                    tipSwitch = false
                    //隐藏通知内容
                    hideContentSwitch = false
                }
            )
        }
        // 闹钟设置
        findViewById<View>(R.id.alarmClock).setOnClickListener {
            val settings = DeviceSettingsMgr.getSetting(WeikeBleMgr.getLastMac())
            WeikeBleMgr.setAlarmClock(settings)
        }
        // 发送当前城市名
        findViewById<View>(R.id.cityName).setOnClickListener {
            WeikeBleMgr.sendCityName("深圳")
        }
        // 同步天气
        findViewById<View>(R.id.weather).setOnClickListener {
            GlobalScope.launch(Dispatchers.IO) {
                val weatherContent = ResourceUtils.readAssets2String("weather.json")
                val weatherAllInfo = Gson().fromJson(weatherContent, WeatherAllInfo::class.java)
                WeikeBleMgr.sendWeather(weatherAllInfo)
            }
        }
        // 设置个人信息
        findViewById<View>(R.id.userInfo).setOnClickListener {
            WeikeBleMgr.setUserInfo(deviceUserModel)
        }
        // 发送联系人
        findViewById<View>(R.id.addContact).setOnClickListener {
            WeikeBleMgr.setAllContact(
                arrayListOf(
                    ContactSettings("张三", "123456789"),
                    ContactSettings("李四", "987654321")
                )
            )
        }
        // 修改联系人
        findViewById<View>(R.id.editContact).setOnClickListener {
            WeikeBleMgr.editContacts(ContactSettings("张三", "1234567890"), 0)
        }
        // 固件升级
        findViewById<View>(R.id.dfuUpdate).setOnClickListener {
            PermissionUtils.permission(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
                .callback(object : SimpleCallback {
                    override fun onGranted() {
                        GlobalScope.launch(Dispatchers.IO) {
                            val dirPath = PathUtils.getExternalAppDownloadPath() + "/ota/"
                            val filePath = dirPath + "ota.zip"
                            FileUtils.createOrExistsDir(dirPath)
                            FileIOUtils.writeFileFromIS(
                                filePath,
                                this@DeviceActivity.assets.open("ota.zip")
                            )
                            WeikeBleMgr.startOta(
                                this@DeviceActivity,
                                WeikeBleMgr.getLastMac(),
                                filePath,
                                object : BaseCallback<Int>() {
                                    override fun callback(code: Int, t: Int) {
                                        Log.i(TAG, "ota code = $code ; msg = $t")
                                        showProgressDialog(code, t, "ota升级中")
                                    }
                                })
                        }
                    }

                    override fun onDenied() {

                    }

                }).request()
        }
        // 表盘推送
        findViewById<View>(R.id.dialPush).setOnClickListener {
            PermissionUtils.permission(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
                .callback(object : SimpleCallback {
                    override fun onGranted() {
                        GlobalScope.launch(Dispatchers.IO) {
                            val dirPath = PathUtils.getExternalAppDownloadPath() + "/ota/"
                            val filePath = dirPath + "dial.zip"
                            FileUtils.createOrExistsDir(dirPath)
                            FileIOUtils.writeFileFromIS(
                                filePath,
                                this@DeviceActivity.assets.open("dial.zip")
                            )
                            WeikeBleMgr.installDial(
                                this@DeviceActivity,
                                WeikeBleMgr.getLastMac(),
                                filePath,
                                object : BaseCallback<Int>() {
                                    override fun callback(code: Int, t: Int) {
                                        Log.i(TAG, "dial push code = $code ; msg = $t")
                                        showProgressDialog(code, t, "表盘推送中")
                                    }
                                })
                        }
                    }

                    override fun onDenied() {

                    }

                }).request()
        }
        // 自定义表盘推送
        findViewById<View>(R.id.customDialPush).setOnClickListener {
            PermissionUtils.permission(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
                .callback(object : SimpleCallback {
                    override fun onGranted() {
                        GlobalScope.launch(Dispatchers.IO) {
                            var bitmap = BitmapFactory.decodeResource(
                                this@DeviceActivity.resources,
                                R.mipmap.img_album_def
                            )
                            val deviceInfoModel =
                                DeviceInfoDao.getDeviceInfoModel(WeikeBleMgr.getLastMac())
                            // 表盘类型 圆or方
                            val isRound = deviceInfoModel.screenType == 0
                            if (isRound) {
                                bitmap = BitmapUtils.getCircleBitmap(bitmap)
                            }
                            if (deviceInfoModel.resolution.size >= 2) {
                                val scaleBitmap =
                                    BitmapUtils.scale(
                                        bitmap,
                                        deviceInfoModel.resolution[0],
                                        deviceInfoModel.resolution[1]
                                    ) ?: return@launch
                                val path = ImageUtil.saveBitMap(scaleBitmap,"${System.currentTimeMillis()}.jpg")
                                val style = DialStyle(255, 255, 255, 1, 0, 1)
                                val model = CustomDialBean(style)
                                model.pathsList.add(path)
                                WeikeBleMgr.installCustomDial(
                                    this@DeviceActivity,
                                    WeikeBleMgr.getLastMac(),
                                    model,
                                    object : BaseCallback<Int>() {
                                        override fun callback(code: Int, t: Int) {
                                            Log.i(TAG, "customDial push code = $code ; msg = $t")
                                            showProgressDialog(code, t, "自定义表盘推送中")
                                        }
                                    })
                            }
                        }
                    }

                    override fun onDenied() {

                    }

                }).request()
        }
        // 同步时间
        findViewById<View>(R.id.syncTime).setOnClickListener { WeikeBleMgr.syncTime() }
        // 连接乘车码
        findViewById<View>(R.id.connectAliCode).setOnClickListener { WeikeBleMgr.beginAliCode() }
        // 断开乘车码
        findViewById<View>(R.id.disconnectAliCode).setOnClickListener { WeikeBleMgr.disconnectAliCode() }
        // 消息内容推送
        findViewById<View>(R.id.msgNotify).setOnClickListener {
            //1：电话 2：挂电话  3：短信  4：mail  5：日历  6：FaceTime  7：QQ  8：Skype  9：WeChat
            //10：WhatsApp  11：Gmail  12：Hangout  13：Inbox  14：Line  15：Twitter  16：Facebook  17：Facebook Messenger  18：Instagram  19：Weibo
            //20：Kakaotalk  21：Facebook page manager  22：Viber  23：Vkclient  24：Telegram  26；snapchat   27：DingTalk  28：alipay   29：Tiktok
            //30：Linkedlln   31：Zalo   32：Whatsapp Business  33: Other
            WeikeBleMgr.setNotifySwitch(33, true)
            WeikeBleMgr.sendNotifyMsg(33, "标题", "这是一条消息")
        }
        // Aigc功能
        findViewById<View>(R.id.aigc).setOnClickListener {
            startActivity(
                Intent(
                    this,
                    AigcActivity::class.java
                )
            )
        }
        // 查询设备可用存储空间
        findViewById<View>(R.id.check_memory).setOnClickListener {
            //0 表盘市场  1 应用市场  2 本地音乐
            AlertDialog.Builder(this)
                .setTitle("选择查询类型")
                .setSingleChoiceItems(
                    arrayOf("表盘市场", "应用市场", "本地音乐"),
                    0
                ) { dialog, which ->
                    WeikeBleMgr.getAvailableMemory(which)
                    dialog.dismiss()
                }.show()
        }
        // 应用推送
        findViewById<View>(R.id.app_push).setOnClickListener {
            PermissionUtils.permission(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
                .callback(object : SimpleCallback {
                    override fun onGranted() {
                        GlobalScope.launch(Dispatchers.IO) {
                            val dirPath = PathUtils.getExternalAppDownloadPath() + "/app/"
                            val filePath = dirPath + "app.zip"
                            FileUtils.createOrExistsDir(dirPath)
                            FileIOUtils.writeFileFromIS(
                                filePath,
                                this@DeviceActivity.assets.open("app.zip")
                            )
                            WeikeBleMgr.installApp(
                                this@DeviceActivity,
                                WeikeBleMgr.getLastMac(),
                                filePath,
                                object : BaseCallback<Int>() {
                                    override fun callback(code: Int, t: Int) {
                                        Log.i(TAG, "app push code = $code ; msg = $t")
                                        showProgressDialog(code, t, "应用推送中")
                                    }
                                })
                        }
                    }

                    override fun onDenied() {

                    }

                }).request()
        }
        // 获取已安装的应用信息
        findViewById<View>(R.id.app_installed_msg).setOnClickListener { WeikeBleMgr.getInstallApp() }
        // 恢复出厂设置
        findViewById<View>(R.id.reset_bond).setOnClickListener { WeikeBleMgr.setResetBand() }
        // 设置二维码名片
        findViewById<View>(R.id.set_qrCode).setOnClickListener {
            // qr: 二维码数据
            // type： 1：微信好友  2：facebook好友  3：QQ好友  4：Twitter好友  5：Whats好友  6：微信收款码  7：支付宝收款码  8：paypal 收款码
            WeikeBleMgr.setQr("", 1)
        }
        // 摇摇拍照
        findViewById<View>(R.id.take_photo).setOnClickListener {
            //0 关闭  1 打开
            AlertDialog.Builder(this)
                .setTitle("设置摇摇拍照状态")
                .setSingleChoiceItems(
                    arrayOf("关闭", "打开"),
                    0
                ) { dialog, which ->
                    WeikeBleMgr.setSharkTakePhoto(which)
                    dialog.dismiss()
                }.show()
        }

        findViewById<View>(R.id.take_gpt).setOnClickListener {
            startActivity(Intent(this, GptExampleActivity::class.java))
        }

        findViewById<View>(R.id.take_physiology).setOnClickListener {
            startActivity(Intent(this, PhysiologyExampleActivity::class.java))
        }

        findViewById<View>(R.id.take_muslim).setOnClickListener {
            startActivity(Intent(this, MuslimExampleActivity::class.java))
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        WeikeBleMgr.unregisterListener(callback)
        WeikeBleMgr.disconnectDevice()
        WeikeBleMgr.disconnectAliCode()
    }

    /**
     * 进度条弹框
     */
    private fun showProgressDialog(code: Int, progress: Int, title: String) {
        when (code) {
            0 -> {
                mProgressDialog.setTitle(title)
                mProgressDialog.progress = 0
                mProgressDialog.show()
            }

            1, 2 -> {
                mProgressDialog.progress = progress
            }

            3, -1 -> mProgressDialog.dismiss()
        }
    }
}